from fastapi import Depends, Request
from nicegui import Client, app, ui
from sqlalchemy.orm import Session


from mobile_frame import mobileframe
from db.db import get_db
from ex4nicegui import bi
import pandas as pd
from ex4nicegui import rxui, to_ref
from db.bs_crud import query_bs_by_name
from ucontrols.add_base_station_dialog import AddBaseStationDialog


class MobileHome:
    def __init__(self, db) -> None:
        self.db = db
        self.page_title = "移动端首页"
        self.df = pd.DataFrame()
        self.ds = bi.data_source(
            self.df
        )  # 绑定一个BiDataSource实例,当变化时可以业面thfc

    # 查询db,得出df
    def query_bs(self, name=""):
        ret = query_bs_by_name(self.db, name)
        self.df = pd.DataFrame([bs.model_dump() for bs in ret])
        # print(self.df.head(10))
        self.ds.reload(self.df)  # 更新数据源，很重要。
        return ret

    def create_lte_freq_record_form(self):
        base_stations = self.query_bs()
        base_station_names = [bs.name for bs in base_stations]
        with ui.card().classes("w-full h-auto bg-sky-300 justify-center"):
            ui.label("LTEFreqRecord 输入表单")
            selected_base_station = ui.select(base_station_names, label="选择基站")
            ui.input(label="LTE 频率记录")
            ui.button(
                "提交",
                on_click=lambda: self.handle_lte_freq_record_submit(
                    selected_base_station.value
                ),
            )

    def handle_lte_freq_record_submit(self, base_station_name):
        print(f"提交的基站: {base_station_name}")
        # 这里可以添加实际的提交逻辑

    # ui template
    def show(self):
        columns = [
            {"label": "ID", "field": "id"},
            {"label": "基站名称", "field": "name"},
            {"label": "经度", "field": "longitude"},
            {"label": "纬度", "field": "latitude"},
            {"label": "基站地址", "field": "address"},
            {"label": "是否天面", "field": "is_rooftop"},
            {"label": "创建时间", "field": "created_at"},
            {"label": "修改时间", "field": "updated_at"},
        ]
        aggrid_columns = [
            {"headerName": "id", "field": "id"},
            {
                "headerName": "基站名称",
                "field": "name",
                "filter": "agTextColumnFilter",
                "floatingFilter": True,
            },
            {"headerName": "经度", "field": "longitude"},
            {"headerName": "纬度", "field": "latitude"},
            {"headerName": "基站地址", "field": "address"},
            {"headerName": "天面", "field": "is_rooftop"},
            {"headerName": "创建时间", "field": "create_datetime"},
            {"headerName": "修改时间", "field": "update_datetime", "hide": True},
            {"headerName": "删除时间", "field": "delete_datetime", "hide": True},
            {"headerName": "isdelete", "field": "is_delete", "hide": True},
        ]
        uid = app.storage.user["uid"]
        username = app.storage.user["username"]
        with mobileframe(self.page_title):
            with ui.card().classes("w-full h-auto bg-sky-300 justify-center"):
                with ui.row():
                    name = ui.input(
                        value="",
                        placeholder="输入基站名称",
                    ).props("color=primary")
                    ui.button("查询", on_click=self.query_bs).props("color=primary")
                    add_bs_dlg = AddBaseStationDialog(self.db)
                    ui.button("新增", on_click=lambda: add_bs_dlg.show()).props(
                        "color=primary"
                    )

            # 用户登录
            # with ui.card().classes("w-full h-full bg-sky-300 justify-center"):
            #     # 表格内容:
            #     self.ds.ui_table(
            #         columns=columns,
            #     ).classes("w-full h-full")
            with ui.card().classes("w-full h-full bg-sky-300 justify-center"):
                self.ds.ui_aggrid(
                    options={
                        "columnDefs": aggrid_columns,
                        "defaultColDef": {
                            "sortable": "true",
                            "resizable": "true",
                            "filter": "true",
                        },
                    },
                )
            self.create_lte_freq_record_form()


@ui.page("/mobile")
def mobile_home(
    db: Session = Depends(get_db),
):
    """
    默认进入的网页，首页
    """
    page = MobileHome(db)
    page.show()


@ui.page("/mobile/test")
def test_get(db: Session = Depends(get_db)):
    """
    4G LTE测试记录管理
    """
    from db.bs_models import BaseStation
    from fastapi.responses import JSONResponse

    tt = db.get(BaseStation, 2)

    print(f"id 2 obj is : {tt.name} id:{tt.id}")
    return JSONResponse({"name": tt.name, "id": tt.id, "len": len(tt.lte_freq_records)})
